import * as vscode from 'vscode'
import { RecordData } from '../types'
import { generateCommentText, getCommentRegex, truncateText } from '../utils/workspace'

export class CommentService {
  // 检测记录是否已有注释
  async hasRecordComment(recordId: number, filePath: string): Promise<boolean> {
    try {
      const document = await vscode.workspace.openTextDocument(filePath)
      const text = document.getText()
      const lines = text.split('\n')

      // 使用更宽松的匹配规则
      const patterns = this.getCommentPatterns(filePath, recordId)

      for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim()
        if (patterns.some(pattern => pattern.test(line))) {
          return true
        }
      }
      return false
    } catch (error) {
      console.error('检测注释失败:', error)
      return false
    }
  }

  // 插入记录注释
  async insertRecordComment(record: RecordData): Promise<void> {
    try {
      const document = await vscode.workspace.openTextDocument(record.filePath)
      const editor = await vscode.window.showTextDocument(document)

      const [startLine] = record.lineRange.split('-').map(Number)
      const insertPosition = new vscode.Position(startLine - 1, 0)

      const problemTitle = truncateText(record.problem, 30)
      const commentText = generateCommentText(record.filePath, record.id, problemTitle)

      await editor.edit(editBuilder => {
        editBuilder.insert(insertPosition, commentText + '\n')
      })

      // 保存文件
      await document.save()
      console.log('插入注释成功并保存文件:', commentText)
    } catch (error) {
      console.error('插入注释失败:', error)
      throw error
    }
  }

  // 更新记录注释
  async updateRecordComment(recordId: number, newProblem: string, filePath: string): Promise<void> {
    try {
      const document = await vscode.workspace.openTextDocument(filePath)
      const editor = await vscode.window.showTextDocument(document)

      const text = document.getText()
      const lines = text.split('\n')
      const patterns = this.getCommentPatterns(filePath, recordId)

      for (let i = 0; i < lines.length; i++) {
        const line = lines[i]
        const trimmedLine = line.trim()

        if (patterns.some(pattern => pattern.test(trimmedLine))) {
          const problemTitle = truncateText(newProblem, 30)
          const newCommentText = generateCommentText(filePath, recordId, problemTitle)

          const lineRange = new vscode.Range(i, 0, i, line.length)
          await editor.edit(editBuilder => {
            editBuilder.replace(lineRange, newCommentText)
          })

          // 保存文件
          await document.save()
          console.log('更新注释成功并保存文件:', newCommentText)
          break
        }
      }
    } catch (error) {
      console.error('更新注释失败:', error)
    }
  }

  // 删除记录注释 - 修复版本
  async deleteRecordComment(recordId: number, filePath: string): Promise<void> {
    try {
      const document = await vscode.workspace.openTextDocument(filePath)
      const editor = await vscode.window.showTextDocument(document)

      const text = document.getText()
      const lines = text.split('\n')
      const patterns = this.getCommentPatterns(filePath, recordId)

      for (let i = 0; i < lines.length; i++) {
        const line = lines[i]
        const trimmedLine = line.trim()

        if (patterns.some(pattern => pattern.test(trimmedLine))) {
          // 修复：只删除当前行，不影响下一行
          const lineRange = new vscode.Range(new vscode.Position(i, 0), new vscode.Position(i + 1, 0))

          await editor.edit(editBuilder => {
            editBuilder.delete(lineRange)
          })

          // 保存文件
          await document.save()
          console.log('删除注释成功并保存文件，记录ID:', recordId, '位置:', i + 1)
          return // 删除成功后立即返回
        }
      }

      console.warn('未找到要删除的注释，记录ID:', recordId)
    } catch (error) {
      console.error('删除注释失败:', error)
      throw error
    }
  }

  /**
   * 获取更宽松的注释匹配模式
   * 支持多种可能的格式变化
   */
  private getCommentPatterns(filePath: string, recordId: number): RegExp[] {
    const fileExtension = filePath.split('.').pop()?.toLowerCase()
    const patterns: RegExp[] = []

    switch (fileExtension) {
      case 'py':
      case 'sh':
      case 'bash':
        patterns.push(new RegExp(`^\\s*#\\s*🔗\\s*CodeMemo记录\\s*#${recordId}\\s*[:：].*$`), new RegExp(`^\\s*#.*CodeMemo.*#${recordId}.*$`))
        break
      case 'html':
      case 'htm':
      case 'xml':
      case 'vue':
        patterns.push(
          new RegExp(`^\\s*<!--\\s*🔗\\s*CodeMemo记录\\s*#${recordId}\\s*[:：].*?\\s*-->\\s*$`),
          new RegExp(`^\\s*<!--.*CodeMemo.*#${recordId}.*-->\\s*$`)
        )
        break
      case 'css':
      case 'scss':
      case 'less':
        patterns.push(
          new RegExp(`^\\s*/\\*\\s*🔗\\s*CodeMemo记录\\s*#${recordId}\\s*[:：].*?\\s*\\*/\\s*$`),
          new RegExp(`^\\s*/\\*.*CodeMemo.*#${recordId}.*\\*/\\s*$`)
        )
        break
      case 'js':
      case 'ts':
      case 'jsx':
      case 'tsx':
      case 'java':
      case 'c':
      case 'cpp':
      case 'h':
      default:
        patterns.push(new RegExp(`^\\s*//\\s*🔗\\s*CodeMemo记录\\s*#${recordId}\\s*[:：].*$`), new RegExp(`^\\s*//.*CodeMemo.*#${recordId}.*$`))
        break
    }

    return patterns
  }

  /**
   * 批量清理文件中的所有CodeMemo注释
   * 用于清理残留的注释
   */
  async cleanupAllComments(filePath: string): Promise<number> {
    try {
      const document = await vscode.workspace.openTextDocument(filePath)
      const editor = await vscode.window.showTextDocument(document)

      const text = document.getText()
      const lines = text.split('\n')
      let removedCount = 0

      // 从后往前删除，避免行号变化问题
      for (let i = lines.length - 1; i >= 0; i--) {
        const line = lines[i].trim()

        // 检查是否是CodeMemo注释
        if (this.isCodeMemoComment(line)) {
          const lineRange = new vscode.Range(new vscode.Position(i, 0), new vscode.Position(i + 1, 0))

          await editor.edit(editBuilder => {
            editBuilder.delete(lineRange)
          })

          removedCount++
          console.log('清理注释:', line.substring(0, 50) + '...')
        }
      }

      if (removedCount > 0) {
        await document.save()
        console.log(`清理完成，共删除 ${removedCount} 条注释`)
      }

      return removedCount
    } catch (error) {
      console.error('批量清理注释失败:', error)
      return 0
    }
  }

  /**
   * 检查是否是CodeMemo注释
   */
  private isCodeMemoComment(line: string): boolean {
    const patterns = [
      /.*🔗.*CodeMemo记录.*#\d+.*/,
      /.*CodeMemo.*#\d+.*/,
      /^<!--.*CodeMemo.*-->$/,
      /^\/\*.*CodeMemo.*\*\/$/,
      /^\/\/.*CodeMemo.*/,
      /^#.*CodeMemo.*/
    ]

    return patterns.some(pattern => pattern.test(line))
  }
}
